<?php
class Geo_Region_model extends MY_Model
{
	public
		$table = 'geo_regions',
		$prKey = 'id'
	;
	
	function __construct()
	{
		parent::__construct();

		$this->fields = array(
			'id' => '',
			'id_countries' 	=> T_('Страна'),
			'id_states' 	=> T_('Область'),
			'name' 			=> T_('Район'),
		);

		$this->rules = array(
			'id_countries' 	=> "trim|strip_tags|required|is_natural_no_zero|max_length[10]",
			'id_states' 	=> "trim|strip_tags|required|is_natural_no_zero|max_length[10]",	
			'name' 			=> "trim|strip_tags|required|max_length[32]",
		);
	}
	
	function getSelectOptions($id_states = null)
	{
		$options = array();
		
		if ($id_states == 0)
		{
			return $options;				
		}
		else if ($id_states != null)
		{
			$this->db->where('id_states', $id_states);
		}
		
		$this->db->order_by('name');
		$query = $this->db->get($this->table);
		
		foreach ($query->result() as $row)
		{
			$options[$row->id] = $row->name; 
		}
		
		return $options;
	}

	function get($id = null)
	{
		$sql = "SELECT r.*, c.id AS id_countries
				FROM geo_regions r, geo_states s, geo_countries c
				WHERE r.id_states=s.id AND s.id_countries=c.id AND r.".$this->prKey."=".$id;
		$query = $this->db->query($sql);
		
		return $query->row_array();
	}

	function hasCities($id_region)
	{
		$sql = 'SELECT COUNT(id) AS num FROM "geo_cities" WHERE id_regions='. $id_region;
		$result = $this->db->query($sql)->row();
		
		return $result->num;
	}

	function search($config = array())
	{
		$config = array_merge(array('rowsOnPage' => 5, 'order' => 'id'), $config);
		if ($this->input->post('per_page'))
		{
			$config['rowsOnPage'] = $this->input->post('per_page');
			$per_page = 0;
		}		
		else if ($this->input->get('per_page'))
		{
			$per_page = $this->input->get('per_page');
		}
		else
		{
			$per_page = 0;
		}

		$order 		= $this->input->get_post('order');
		$direction 	= $this->input->get_post('direction');
		$search 	= $this->input->get_post('search');
		$id_states  = $this->input->get_post('id_states');

		// main sql		
		$sql = '';
		$sql .= ' FROM '.$this->table.' r, geo_states s, geo_countries c';
		$sql .= ' WHERE r.id_states=s.id AND s.id_countries=c.id ';  
			
		if ($search)
		{
			$sql .= ' AND r.name LIKE ' . $this->db->escape('%' . $search . '%'); 
		}
		
		switch ($order)
		{
			default:
				$sql .= ' ORDER BY r.id';
				$direction = 'DESC';
		}
		
		$sql .= ($direction == 'DESC') ? ' DESC' : ' ASC';

		// pagination config
		$config['base_url'] = Xurl_add(Xregenerate_url('per_page,search', true), 'search', $search);
		$config['per_page'] = $config['rowsOnPage'];
		//$config['total_rows'] = $this->getRowCount($sql);

		//$this->pagination->initialize($config); 
		
		// main sql
		$sql = 'SELECT r.*, s.name AS state_name, c.name AS country_name' . $sql;// . sprintf(' LIMIT %d, %d', $per_page, $config['per_page']); 

		$this->data['list'] = $this->db->query($sql)->result();

		$this->data['per_page']  = $per_page;
		$this->data['search'] 	 = $search;
		$this->data['id_states'] = $id_states;  
	}	
	
	function delete($items_serialized = null)
	{
		$items = explode("&", $items_serialized);
		
		$report = "";
		foreach ($items as $id)
		{	
			if ($this->geo_region_model->hasCities($id) > 0)
			{
				$this->log->writeMessage('error', T_('Для этого района заданы города. Удаление невозможно.'));
				$report .= ",0"; // don't deleted
			}
			else
			{
				$data = $this->geo_region_model->get($id);
				
				$res = $this->db->delete($this->table, array($this->prKey => $id));				
				
				if (is_null($res))
				{
					$this->log->writeMessage('error', T_('Error. Район не удален.'));
					$report .= ",0"; // don't deleted
				}
				else
				{
					$this->log->writeMessage('done', T_('Район удален.'));
					$report .= ",1"; // deleted
					
			        $log['id_admins'] = $this->auth->getID();
			        $log['message']   = T_('Район <span class="green">'). $data['name'] . T_('</span> удален.');
			        $log['location']  = $_SERVER['REQUEST_URI'];
			        $log['data']      = serialize($data);
			        $this->watchdog_model->insert($log);
				}				
			}						
		}
		
		return substr($report, 1);
	}

	function insert($data)
	{
		if (!empty($data))
		{
			parent::insert($data);

			if ($this->db->insert_id() > 0)
			{
				$this->log->writeMessage('done', T_('Район успешно добавлен.'));
				
				return TRUE;
			}
			else
			{
				$this->log->writeMessage('error', T_('Error! Район не создан.'));
				
				return FALSE;
			}
		}		
	}

	function update($data)
	{
		if (!empty($data))
		{
			$res = parent::update($data);

			$this->log->writeMessage('done', T_('Измененные данные сохранены.'));

			return TRUE;			
		}		
	}		
}
?>